/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL || head->next == NULL) {
            return head;
        }

        ListNode *cur = head;
        ListNode *pre = NULL;

        while (cur) {
            ListNode *t = cur->next;
            while (t && t->val == cur->val) {
                t = t->next;
            }
            if (cur->next != t) {
                if (pre == NULL) {
                    head = t;
                } else {
                    pre->next = t;
                }
                cur = t;
            } else {
                pre = cur;
                cur = t;
            }
        }
        return head;
    }
};
